import axios from 'axios'
import store from '@/store'
import { Toast, Notify, Dialog } from 'vant'
// 根据环境不同引入不同api地址
import { baseApi } from '@/config'
// import router from '@/router'
// create an axios instance

const service = axios.create({
  baseURL: baseApi, // url = base api url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const [SUCCESS_CODE, ERROR_CODE, UNAUTHORIZED] = [0, 1, 401]
const [illegalToken, otherClientsLogged, tokenExpired] = [50008, 50012, 50014]

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true
      })
    }
    const token = store.getters.token
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    const { code, msg } = res
    if (code === SUCCESS_CODE) return res
    if (code === UNAUTHORIZED) {
      Dialog.alert({
        message: msg || '登录认证失败，请重新登录',
        theme: 'round-button'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => { location.reload() })
      })
    } else {
      if (res.msg) {
        Toast.fail(res.msg)
      }
    }
    return res
    // return Promise.reject(new Error(res.msg || 'Error'))
  },
  error => {
    Toast.clear()
    Notify({ type: 'warning', message: '网络连接错误' })
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
